package com.wswy.wzcx.ui.car.remind

import android.app.DatePickerDialog
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.CarTypes
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.utils.append0
import kotlinx.android.synthetic.main.fragment_add_inspection.btn_save
import kotlinx.android.synthetic.main.fragment_add_inspection.tv_car_no
import kotlinx.android.synthetic.main.fragment_add_new_inspection.*
import java.util.*
import kotlin.math.max

/**
 * 添加年检
 */
class InspectionNewAddFragment : CBaseFragment(), RadioGroup.OnCheckedChangeListener {


    private lateinit var remindViewModel: RemindViewModel
    private lateinit var mCarTypes: Array<String>

    private var mannedNum = "1"  //车辆类型
    private var natureOfUse = "2"  //使用性质
    private var inspectReminder = "0"  //年检提醒

    private val CAR_TYPES = arrayOf(
            Pair("小型车", CarTypes.CAR_SMALL),
            Pair("大型车", CarTypes.CAR_BIG),
            Pair("摩托车", CarTypes.MOTO),
            Pair("新能源(小车)", CarTypes.NE_CAR_SMALL),
            Pair("新能源(大车)", CarTypes.NE_CAR_BIG)
            //Pair<String,String>("新能源",CarTypes.NE_CAR_SMALL)
            //Pair<String,String>("挂车","15")
    )
    private var currentCarType: String? = CarTypes.CAR_SMALL
    private lateinit var mCarTypeIndexs: Array<String>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_add_new_inspection, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        remindViewModel = provideViewModelFromActivity(RemindViewModel::class.java)
        remindViewModel.loadCompany()
        tv_car_no.text = remindViewModel.userCarInfo.carNo

        seat_radio_group.setOnCheckedChangeListener(this)
        nature_radio_group.setOnCheckedChangeListener(this)

        UiUtils.addOnGlobalLayoutListener(tv_hint_desc_new_title) {
            ContextCompat.getDrawable(tv_hint_desc_new_title.context, R.drawable.add_car_line)?.let { drawable ->
                tv_hint_desc_new_title.layoutParams?.run {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    tv_hint_desc_new_title.layoutParams = this
                }
                (tv_hint_desc_new_title.parent as? View)?.width?.minus(tv_hint_desc_new_title.width)?.div(2)?.let {
                    tv_hint_desc_new_title.compoundDrawablePadding = SizeUtils.dp2px(12f)
                    drawable.setBounds(0, 0, it - tv_hint_desc_new_title.compoundDrawablePadding, SizeUtils.dp2px(1f))
                    tv_hint_desc_new_title.setCompoundDrawables(drawable, null, drawable, null)
                }

            }

        }

        remindViewModel.userCarInfo.carExtendInfo?.inspection?.run {
            tv_registered_date.text = regDate
            v_choose_validity_new_date.text = validityDate
            remindViewModel.addInspectionSaveChoose(regDate, validityDate)
        }

        //注册日期
        tv_registered_date.onClick {
            val ymd = remindViewModel.addInspectionStatus.getYMD(remindViewModel.addInspectionStatus.regDate)
            ymd?.set(1, ymd[1] - 1)
            showChooseDate(Calendar.getInstance().timeInMillis, ymd ?: arrayOf(2018, 0, 1)) {
                tv_registered_date.text = it
                remindViewModel.calInspectionData(it)
                remindViewModel.addInspectionSaveChoose(regDate = it)
            }
        }

        v_choose_validity_new_date.onClick {
            val ymd = remindViewModel.addInspectionStatus.getYMD(remindViewModel.addInspectionStatus.validityDate)
            ymd?.set(1, ymd[1] - 1)
            showChooseDate(ymd = ymd ?: arrayOf(2018, 0, 1)) {
                v_choose_validity_new_date.text = it
                remindViewModel.addInspectionSaveChoose(validityDate = it)
            }
        }

        remindViewModel.getCalInspectionDate().observe(this, android.arch.lifecycle.Observer {
            it?.run {
                if (TextUtils.equals(tv_registered_date.text.toString(), regDate)) {
                    //更新时间
                    v_choose_validity_new_date.text = endDate
                }
            }
        })

        //选择车辆类型
        ll_choose_car_new_type.onClick {
            showChooseCarType {
                tv_car_new_type.text = it.first
                currentCarType = it.second
            }
        }
        //选择年检到期提醒
        switch_new_notify.onClick {
            val tmp = switch_new_notify.isChecked
            switch_new_notify.toggle()
            inspectReminder = if (tmp) {
                "1"
            } else {
                ""
            }
        }
        //保存
        btn_save.onClick {
            save()
        }
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.seat_one_button -> {
                mannedNum == "1"
                seat_one_button.setTextColor(getColor(R.color.clr_295AF5))
                seat_two_button.setTextColor(getColor(R.color.clr_383838))
                seat_one_button.isChecked = true
                seat_two_button.isChecked = false
            }

            R.id.seat_two_button -> {
                mannedNum == "2"
                seat_two_button.setTextColor(getColor(R.color.clr_295AF5))
                seat_one_button.setTextColor(getColor(R.color.clr_383838))
                seat_one_button.isChecked = false
                seat_two_button.isChecked = true
            }

            R.id.operation -> {
                natureOfUse == "1"
                operation.setTextColor(getColor(R.color.clr_295AF5))
                the_operating.setTextColor(getColor(R.color.clr_383838))
                operation.isChecked = true
                the_operating.isChecked = false
            }

            R.id.the_operating -> {
                natureOfUse == "2"
                the_operating.setTextColor(getColor(R.color.clr_295AF5))
                operation.setTextColor(getColor(R.color.clr_383838))
                the_operating.isChecked = true
                operation.isChecked = false
            }
        }
    }

    //选择车型
    private fun showChooseCarType(block: ((Pair<String, String>) -> Unit)) {
        if (!this::mCarTypes.isInitialized) {
            mCarTypes = CAR_TYPES.map { it.first }.toTypedArray()
        }
        if (!this::mCarTypeIndexs.isInitialized) {
            mCarTypeIndexs = CAR_TYPES.map { it.second }.toTypedArray()
        }
        AlertDialog.Builder(activity!!).apply {
            setTitle("选择车辆类型")
            val st = arrayOf(max(mCarTypeIndexs.indexOfFirst { TextUtils.equals(it, currentCarType) }, 0))
            setSingleChoiceItems(mCarTypes, st[0]) { _, which ->
                st[0] = which
            }

            setPositiveButton(R.string.ok) { dialog, _ ->
                val idx = st[0]
                block.invoke(Pair(mCarTypes[idx], mCarTypeIndexs[idx]))
                dialog.dismiss()
            }

            setNegativeButton(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }

        }.run {
            show()
        }
    }

    private fun save() {
        if (tv_registered_date.text == "请选择注册登记日期") {
            ToastUtils.showText("请选择上牌时间")
            return
        }
        if (v_choose_validity_new_date.text == "请选择校验有效期至") {
            ToastUtils.showText("请选择有效期")
            return
        }

        StatTools.sendClick(context, StatisticsId.addinspection_save)
        val dialog = LoadingDialog(context, "")
        remindViewModel.addInspection(tv_registered_date.text?.toString(), v_choose_validity_new_date.text?.toString(),
                mannedNum, currentCarType, natureOfUse, inspectReminder)
        remindViewModel.getAddInsuranceLiveData().observe(this, android.arch.lifecycle.Observer {

            it?.run {
                btn_save.isClickable = !inLoading()
                if (inLoading()) {
                    dialog.show()
                } else {
                    if (isOk()) {
                        dialog.setOnDismissListener {
                            (activity as? RemindActivity)?.run {
                                showInfo()
                            }
                        }
                        dialog.setSuccess("保存成功")
                        remindViewModel.setCarExtendInfo(data)

                    } else {

                        dialog.setSuccess("保存失败")
                    }
                }
            }
        })
    }


    private fun showChooseDate(maxDate: Long = 0, ymd: Array<Int>, block: ((String) -> Unit)) {
        DialogFactory.createDatePickerDialog(context, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
            remindViewModel.addInsuranceSaveChoose(year, month, dayOfMonth)
            block.invoke("$year-${(month + 1).append0()}-${dayOfMonth.append0()}")

        }, ymd[0], ymd[1], ymd[2])
                .run {
                    //val datePicker = datePicker
                    if (maxDate > 0) {
                        datePicker.maxDate = maxDate
                    }
                    show()
                }
    }
}